package conf

import (
	"flag"
	"log"
	"time"

	"github.com/go-ini/ini"
)

var cfg *ini.File

type App struct {
	JwtSecret string
	NAME      string
}

var AppConf = &App{}

type Server struct {
	RunMode      string
	HttpPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

var ServerConf = &Server{}

type Database struct {
	Type     string
	User     string
	Password string
	Host     string
	Name     string
}

var DatabaseConf = &Database{}

type Redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
	DB          string
}

var RedisConf = &Redis{}

type Wechat struct {
	AppID          string
	AppSecret      string
	Token          string
	EncodingAESKey string
}

var WechatConf = &Wechat{}

type Lgz struct {
	AccessKey    string
	AssessSecret string
}

var LgzConf = &Lgz{}

func init() {
	var err error
	prod := flag.String("prod", "", "Input your prod")
	flag.Parse()
	if *prod == "release" {
		cfg, err = ini.Load("conf/app.ini")
	} else {
		cfg, err = ini.Load("conf/dev.ini")
	}
	if err != nil {
		log.Fatalf("Fail to parse 'conf/app.ini': %v", err)
	}
	mapTo("redis", RedisConf)
	mapTo("app", AppConf)
	mapTo("server", ServerConf)
	mapTo("database", DatabaseConf)
	mapTo("wechat", WechatConf)
	mapTo("lgz", LgzConf)
	ServerConf.ReadTimeout = ServerConf.ReadTimeout * time.Second
	ServerConf.WriteTimeout = ServerConf.ReadTimeout * time.Second
}

func mapTo(section string, v interface{}) {
	err := cfg.Section(section).MapTo(v)
	if err != nil {
		log.Fatalf("Cfg.MapTo %v err: %v", section, err)
	}
}
